package com.ecmcloud.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ecmcloud.api.ApiStrategyFactory;
import com.ecmcloud.common.dto.Result;
import com.ecmcloud.constants.StatusEnum;
import com.ecmcloud.entity.User;
import com.ecmcloud.service.ILoginService;
import com.ecmcloud.service.IUserService;
import com.ecmcloud.vo.UserVO;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 */
@Service
public class LoginServiceImpl implements ILoginService {
	
	@Autowired
    private IUserService userService;
    
    /**
     * 登录
     *
     * @param userVO
     * @return
     */
    @Override
    public Result<SaTokenInfo> login(UserVO userVO) {
        String phone = userVO.getPhone();
        String password = userVO.getPassword();
        User u = userService.lambdaQuery().eq(User::getPhone, phone).eq(User::getPassword, password).eq(User::getStatus, StatusEnum.ENABLE.getValue()).one();
        if (u == null) {
            return Result.fail("账号或者密码错误");
        }
        StpUtil.login(u.getId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();

        return Result.success(tokenInfo);
    }

    /**
     * token登录
     *
     * @param token
     * @return
     */
    @Override
    public Result<SaTokenInfo> loginByToken(String token) {
        String userId = ApiStrategyFactory.getStrategy().getUserIdByToken(token);
        StpUtil.login(userId);
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return Result.success(tokenInfo);
    }

    /**
     * 退出登录
     *
     * @return
     */
    @Override
    public Result<String> logout() {
        StpUtil.logout();
        return Result.success();
    }

}
